(function() {
    "use strict";

    /**
     * @ngdoc directive
     * @name webApp.directive:loginDialog
     * @description
     * # loginDialog
     */
    angular
        .module("webApp")
        .run([
            "$templateCache",
            "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.logindialog.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive("loginDialog", [
            "$rootScope",
            "helper",
            function($rootScope, helper) {
                return {
                    restrict: "EA",
                    template: "<span></span>",
                    scope: {},
                    controller: [
                        "$scope",
                        "authService",
                        "sessionService",
                        "dataService",
                        "$compile",
                        "helper",
                        "$templateCache",
                        "base64",
                        "$timeout",
                        "ERP_CONFIG",
                        function(
                            $scope,
                            authService,
                            sessionService,
                            dataService,
                            $compile,
                            helper,
                            $templateCache,
                            base64,
                            $timeout,
                            ERP_CONFIG
                        ) {
                            $scope.loginName = ""; //
                            $scope.loginPwd = ""; //dhf123456789

                            $scope.checking = true; //是账号登录还是二维码扫描登录
                            $scope.isopen = false; //是否已弹出窗口，防止多次弹出

                            function setIsOpen(r) {
                                $scope.isopen = r;
                            }

                            $scope.cleanCache = function($event) {
                                dataService.removeAllCache();
                                helper.myTip("success", $event.currentTarget);
                            };

                            this.closeWin = function() {
                                loadingToggle(true);
                                if ($scope.loginWin) {
                                    $scope.loginWin.modal("hide");
                                }
                            };

                            this.init = function() {
                                //随机码
                                if (ERP_CONFIG.debug) {
                                    $scope.randkey = "1212fdsafrgsafsdaf";
                                } else {
                                    $scope.randkey = helper.guid24();
                                }
                                if (ERP_CONFIG.debug) {
                                    $scope.jastring = ERP_CONFIG.qrLoginUrlDev + $scope.randkey;
                                } else {
                                    $scope.jastring = ERP_CONFIG.qrLoginUrlPro + $scope.randkey;
                                }
                                getImage($scope.jastring).then(this.showLogin);
                            };
                            $scope.initData = this.init;

                            function getImage(jastring) {
                                if (ERP_CONFIG.debug) {
                                    return qrcode(jastring);
                                } else {
                                    return dataService
                                        .acodeunlimitGet(
                                            ERP_CONFIG.BackAppId,
                                            "AUTR" + $scope.randkey,
                                            true,
                                            "pages/admin/index/index"
                                        )
                                        .then(function(r) {
                                            if (r && r.Msg) {
                                                return qrcode(jastring);
                                            } else {
                                                $scope.dataimage = "data:image/png;base64," + r;
                                                return r;
                                            }
                                        });
                                }
                            }

                            function qrcode(jastring) {
                                return dataService
                                    .webQrcodeGet({ code: jastring })
                                    .then(function(redata) {
                                        $scope.dataimage = "data:image/png;base64," + redata;
                                        return redata;
                                    });
                            }

                            $scope.showIsvLogin = function() {
                                $timeout(function() {
                                    $scope.isIsvLogin = !$scope.isIsvLogin;
                                    if ($scope.isIsvLogin) {
                                        $scope.checking = false;
                                    } else {
                                        $scope.checking = true;
                                        getToken();
                                    }
                                });
                            };
                            $scope.showAccountLogin = function() {
                                $timeout(function() {
                                    $scope.isAccountLogin = !$scope.isAccountLogin;
                                    if ($scope.isAccountLogin) {
                                        $scope.checking = false;
                                    } else {
                                        $scope.checking = true;
                                        getToken();
                                    }
                                });
                            };

                            this.showLogin = function() {
                                loadingToggle(false);
                                $scope.error = null;
                                //弹出
                                $scope.loginWin = $.alert({
                                    backdrop: "static",
                                    keyboard: false,
                                    title: '<span ng-if="!isAccountLogin"><span ng-if="!isIsvLogin">{{"登录|注册"|translate}}</span><span ng-if="isIsvLogin">{{"管理员登录"|translate}}</span></span><span ng-click="showIsvLogin()" style="width:10px;height:10px;display: inline-block;" > </span><span ng-if="isAccountLogin">{{"账号密码登录"|translate}} <span ng-click="showAccountLogin()" style="width:10px;height:10px;display: inline-block;" > </span></span>',
                                    body: $templateCache.get("views/directives.logindialog.html"),
                                    okBtn: '{{"login"|translate}}',
                                    closeBtn: false,
                                    hasfoot: false,
                                    transition: true,
                                    width: "small",
                                    show: function(e) {
                                        getToken();
                                        $compile($(e.currentTarget).contents())($scope);
                                    },
                                    okHide: function(e) {
                                        $scope.checking = false;
                                        setIsOpen(false);
                                    },
                                    shown: function(e) {
                                        loadingToggle(false);
                                    }
                                });
                            };

                            $scope.accountLogin = function() {
                                dataService
                                    .sellerLogin(
                                        $scope.loginName,
                                        $scope.loginPwd,
                                        $scope.selpartner_id
                                    )
                                    .then(function(redata) {
                                        if (redata.Msg) {
                                            helper.message(redata.Msg, 'error');
                                        } else if (redata.token) {
                                            setIsOpen(false);
                                            authService.loginConfirmed("success", function(config) {
                                                //通知完成加载
                                                $rootScope.$broadcast("event:store-update");
                                                //自动追加token
                                                config.data["token"] = redata.token;
                                                return config;
                                            });
                                            rmAlert();
                                        } else {
                                            if (redata.partner_id_names && !$scope.selpartner_id) {
                                                $scope.partner_id_names = redata.partner_id_names;
                                            }
                                        }
                                    });
                            };
                            $scope.change = function(selPartner) {
                                _.map($scope.partner_id_names, function(da, key) {
                                    if (selPartner == da) {
                                        $scope.selpartner_id = key;
                                    }
                                });
                            };

                            $scope.isvLogin = function(loginName, iloginPwd) {
                                dataService
                                    .isvLogin(loginName, iloginPwd)
                                    .then(function(redata) {
                                        if (redata.token) {
                                            setIsOpen(false);
                                            authService.loginConfirmed("success", function(config) {
                                                //自动追加token
                                                config.data["token"] = redata.token;
                                                return config;
                                            });
                                            rmAlert();
                                        }
                                    });
                            };

                            function getToken() {
                                dataService
                                    .webTokenGet({ identity_id: $scope.randkey })
                                    .then(function(redata) {
                                        if (redata.token) {
                                            setIsOpen(false);
                                            authService.loginConfirmed("success", function(config) {
                                                //通知完成加载
                                                $rootScope.$broadcast("event:store-update");
                                                //自动追加token
                                                config.data["token"] = redata.token;
                                                return config;
                                            });
                                            rmAlert();
                                            // loadingToggle(false);
                                        } else {
                                            if ($scope.checking) {
                                                $timeout(getToken, 1000);
                                            }
                                        }
                                    });
                            }
                        }
                    ],

                    link: function(scope, elem, attrs, ctr) {
                        scope.$on("event:auth-loginRequired", function() {
                            if (!scope.isopen) {
                                scope.isopen = true;
                                ctr.init();
                            } else {
                                // console.log("已弹出。。。");
                            }
                        });
                        scope.$on("event:auth-loginConfirmed", function() {});
                        scope.$on("event:close_login_win", function() {
                            ctr.closeWin();
                        });
                        //通知完成加载
                        $rootScope.$broadcast("event:login-dialog-init-done");
                    }
                };
            }
        ]);
})();